package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程任务负责与指定的客户端完成HTTP交互
 * 每次HTTP交互都采取一问一答的规则，因此交互由三步来完成:
 * 1:解析请求
 * 2:处理请求
 * 3:发送响应
 */

public class ClientHandler implements Runnable{

    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //1解析请求
            //1.1解析请求行
            String line = readline();
            System.out.println(line);

            //请求行的相关信息
            String method;//请求方式
            String uri;//抽象路径
            String protocol;//协议

            //将请求行内容拆分出来并分别赋值给三个变量
            String[] arr = line.split("\\s");
            method = arr[0];
            uri = arr[1];
            protocol = arr[2];

            //测试路径:http://localhost:8088/myweb/index.html
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);

            //1.2解析消息头
            //消息头相关信息
            Map<String,String> headers = new HashMap<>();
            while (true){
                line = readline();
                if (line.isEmpty()){//若读取的字符串为空串,说明单独读取了回车+换行
                    break;
                }
                System.out.println("消息头:"+line);
                //将消息头的名字和值以key,value形式存入headers这个Map中
                String[] arr1 =line.split(": ");
                headers.put(arr1[0],arr1[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readline() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuffer sb = new StringBuffer();
        int d;
        char pre = 'a',cur = 'a';//pre上一次读取的字符 cur本次读取到的字符
        while ((d = in.read()) != -1){
            cur = (char)d;
            if (pre == 13 & cur ==10){
                break;
            }
            sb.append(cur);
            pre = cur;
        }
        return sb.toString().trim();
    }
}
